package org.example.test.test;

import cn.hutool.core.util.StrUtil;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 赎金信
 * 给你两个字符串：ransomNote 和 magazine ，判断 ransomNote 能不能由 magazine 里面的字符构成。
 * 先给容器里面装magazine，再从容器里面取ransomNote
 */
public class CanConstruct {
    public static void main(String[] args) {
        System.out.println(canConstruct2("aa", "aab"));
    }

    public static boolean canConstruct(String ransomNote, String magazine) {
        HashMap<String, Integer> map = new HashMap<>();
        for (String s : magazine.split("")) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }
        for (String s : ransomNote.split("")) {
            if (!map.containsKey(s)) {
                return false;
            } else {
                Integer i = map.get(s);
                if (i == 0) {
                    return false;
                } else {
                    map.put(s, i - 1);
                }
            }
        }
        return true;
    }

    public static boolean canConstruct2(String ransomNote, String magazine) {
        int[] arr = new int[32];
        for (int i = 0; i < magazine.length(); i++) {
            char c = magazine.charAt(i);
            arr[c - 'a'] = arr[c - 'a'] + 1;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            arr[c - 'a'] = arr[c - 'a'] - 1;
            if (arr[c - 'a'] < 0) {
                return false;
            }
        }
        return true;
    }
}
